package indi.h.devmg.acquisition.snmp.mib.rules;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import indi.h.devmg.acquisition.snmp.mib.beans.Import;
import indi.h.devmg.acquisition.snmp.mib.beans.MIB;
import indi.h.devmg.acquisition.snmp.mib.util.ArrayFormat;

public class ImportsRule implements Rule<Map<String, Import>> {
	private String[] sons;
	private MIB mib;
	private boolean end;
	private Map<String, Import> imports;

	public ImportsRule(MIB mib) {
		this.mib = mib;
		this.end = false;
		this.imports = new HashMap<>();
	}

	@Override
	public void init(String s) {
		// TODO Auto-generated method stub
		this.mib.setImports(imports);
	}

	@Override
	public Map<String, Import> getTarget() {
		// TODO Auto-generated method stub
		return this.imports;
	}

	@Override
	public int addData(String s) {
		// TODO Auto-generated method stub
		if (end)
			return 1;
		if (s.endsWith(";"))
			end = true;
		if (s.indexOf("FROM") >= 0) {
			String[] split = s.split("FROM");
			String trim = split[1].trim();
			trim = trim.endsWith(";") ? trim.substring(0, trim.length() - 1) : trim;
			Import imp = new Import(trim);
			
			List<String> split2 = ArrayFormat.removeEmpty(split[0].trim().split(","));
			
			if (sons != null) {

				String[] nodes = new String[sons.length + split2.size()];

				System.arraycopy(sons, 0, nodes, 0, sons.length);

				System.arraycopy(split2.toArray(), 0, nodes, sons.length, split2.size());

				List<String> asList = Arrays.asList(nodes);

				imp.setNodes(asList);

			} else {
				imp.setNodes(split2);

			}

			this.imports.put(imp.getParent(), imp);

			sons = null;
		} else {
			String[] split2 = s.trim().split(",");
			if (sons != null) {
				String[] nodes = new String[sons.length + split2.length];
				System.arraycopy(sons, 0, nodes, 0, sons.length);
				System.arraycopy(split2, 0, nodes, sons.length, split2.length);
				sons = nodes;
			} else {
				sons = split2;
			}
		}
		return 0;
	}

	public static void main(String[] args) {
		String[] s = { "IMPORTS", "OBJECT-TYPE, Counter32, Gauge32", "FROM SNMPv2-SMI", "mib-2", "FROM RFC1213-MIB",
				"DisplayString, TimeStamp", "FROM SNMPv2-TC;" };
		ImportsRule mr = new ImportsRule(new MIB());
		mr.init(s[0]);
		for (int i = 1; i < s.length; i++) {
			mr.addData(s[i]);
		}
		
		System.out.println(mr.getTarget().size());
	}
}
